// 用户服务层

import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import { Op } from 'sequelize'
import { User } from '../models/index.js'
import { UserTypes } from '../types/index.js'

/**
 * 创建用户
 */
const createUser = async (userData) => {
  const { username, password } = userData
  
  // 检查用户是否已存在
  const existingUser = await User.findOne({
    where: { username }
  })
  
  if (existingUser) {
    throw new Error('用户名已存在')
  }
  
  // 加密密码
  const hashedPassword = await bcrypt.hash(password, 10)
  
  // 创建用户
  const user = await User.create({
    username,
    password: hashedPassword,
    role: UserTypes.ROLES.USER
  })
  
  return user
}

/**
 * 验证用户登录
 */
const authenticateUser = async (username, password) => {
  const user = await User.findOne({
    where: { username }
  })
  
  if (!user) {
    throw new Error('用户不存在')
  }
  
  const isValidPassword = await bcrypt.compare(password, user.password)
  
  if (!isValidPassword) {
    throw new Error('密码错误')
  }
  
  return user
}

/**
 * 生成JWT令牌
 */
const generateToken = (user) => {
  return jwt.sign(
    { 
      id: user.id, 
      username: user.username,
      role: user.role 
    },
    process.env.JWT_SECRET,
    { expiresIn: '7d' }
  )
}

/**
 * 获取用户资料
 */
const getUserProfile = async (userId) => {
  const user = await User.findByPk(userId, {
    attributes: { exclude: ['password'] }
  })
  
  if (!user) {
    throw new Error('用户不存在')
  }
  
  return user
}

/**
 * 更新用户资料
 */
const updateUserProfile = async (userId, profileData) => {
  const user = await User.findByPk(userId)
  
  if (!user) {
    throw new Error('用户不存在')
  }
  
  // 只允许更新特定字段
  const allowedFields = ['title', 'bio', 'avatar', 'siteTitle', 'siteSubtitle']
  const updateData = {}
  
  allowedFields.forEach(field => {
    if (profileData[field] !== undefined) {
      updateData[field] = profileData[field]
    }
  })
  
  await user.update(updateData)
  
  return user
}

export default {
  createUser,
  authenticateUser,
  generateToken,
  getUserProfile,
  updateUserProfile
} 